#include <unistd.h>
#include <functional>
#include "ThreadPool.h"

using EnQue = SyncQueue<int>;

EnQue enque;

void producer_func(const int id) {
    while(1){
        int item = id * 100 + rand() % 100; // 示例数据
        printf("Producer %lu produced item %d\n", pthread_self(), item);
        enque.Put(item);
        usleep(rand() % 1000000); // 模拟生产间隔
    }
    return ;
}

void consumer_func() {
    int item = 0;
    while(1) {
        enque.Take(item);
        printf("Consumer %lu consumed item %d\n", pthread_self(), item);
        usleep(rand() % 1000000); // 模拟消费间隔
    }
    return ;
}

// NOTE 使用线程池实现生产者和消费者
int main() {
    ThreadPool tp(5);
    tp.AddTask(std::bind(&producer_func, 555));
    std::this_thread::sleep_for(std::chrono::seconds(1));
    tp.AddTask(std::bind(&producer_func, 666));
    std::this_thread::sleep_for(std::chrono::seconds(1));
    tp.AddTask(std::bind(&consumer_func));
    std::this_thread::sleep_for(std::chrono::seconds(1));
    tp.AddTask(std::bind(&consumer_func));
    std::this_thread::sleep_for(std::chrono::seconds(1));
    tp.AddTask(std::bind(&consumer_func));
    std::this_thread::sleep_for(std::chrono::seconds(30));
    enque.Stop();
    tp.Stop();
    return 0;
}
